import apiClient from './client'
import type { LoginRequest } from '@/types'

const isDev = import.meta.env.DEV
const MOCK_ADMIN = { username: 'admin', password: 'admin123' }

// 统一构造前端本地 mock 的响应，保持与后端 ResponseResult<T> 结构一致
function mockResponse<T>(data: T): Promise<{ data: { code: number; msg: string; data: T } }> {
  return Promise.resolve({
    data: {
      code: 200,
      msg: 'OK',
      data,
    },
  })
}

export const adminService = {
  // ===== 后台管理员模块 (/admin) =====

  // 管理员登录
  login: (credentials: LoginRequest) => {
    if (
      isDev &&
      credentials.username === MOCK_ADMIN.username &&
      credentials.password === MOCK_ADMIN.password
    ) {
      // 前端本地 mock：开发模式下拦截，返回成功
      return mockResponse<boolean>(true)
    }
    return apiClient.post<boolean>('/api/admin/login', undefined, {
      params: { username: credentials.username, password: credentials.password },
    })
  },

  // 管理员退出登录
  logout: () => {
    if (isDev && localStorage.getItem('userType') === 'admin') {
      return mockResponse<boolean>(true)
    }
    return apiClient.post('/api/admin/logout')
  },

  // 管理员 token 校验（用于刷新/重载后的持久化校验）
  verifyToken: () => {
    // 如果是开发模式且有本地管理员状态，返回 mock 响应
    if (isDev && localStorage.getItem('userType') === 'admin') {
      return mockResponse<boolean>(true)
    }
    // 调用真实的后端 token 验证接口
    return apiClient.post('/api/admin/verify-token')
  },

  // ===== 广告管理模块 (/api/v1/advertisements) =====

  // 分页并搜索广告列表
  getAdvertisementsList: (pageNum: number = 1, pageSize: number = 20, keyword?: string) =>
    apiClient.get<import('@/types').PageInfo<import('@/types').Advertisement>>(
      '/api/v1/advertisements/list',
      {
        params: { pageNum, pageSize, keyword },
      },
    ),

  // 新增广告
  addAdvertisement: (advertisementData: Partial<import('@/types').Advertisement>) =>
    apiClient.post<boolean>('/api/v1/advertisements/add', advertisementData),

  // 更新广告
  updateAdvertisement: (id: number, advertisementData: Partial<import('@/types').Advertisement>) =>
    apiClient.post<boolean>(`/api/v1/advertisements/update/${id}`, advertisementData),

  // 删除单个广告
  deleteAdvertisement: (id: number) => apiClient.post(`/api/v1/advertisements/delete/${id}`),

  // 批量删除广告
  batchDeleteAdvertisements: (ids: number[]) =>
    apiClient.post('/api/v1/advertisements/delete/batch', ids),

  // ===== 合作链接管理模块 (/api/v1/partner-links) =====

  // 分页并搜索合作链接列表
  getPartnerLinksList: (pageNum: number = 1, pageSize: number = 20, keyword?: string) =>
    apiClient.get<import('@/types').PageInfo<import('@/types').PartnerLink>>(
      '/api/v1/partner-links/list',
      {
        params: { pageNum, pageSize, keyword },
      },
    ),

  // 新增合作链接
  addPartnerLink: (partnerLinkData: Partial<import('@/types').PartnerLink>) =>
    apiClient.post<boolean>('/api/v1/partner-links/add', partnerLinkData),

  // 更新合作链接
  updatePartnerLink: (id: number, partnerLinkData: Partial<import('@/types').PartnerLink>) =>
    apiClient.post<boolean>(`/api/v1/partner-links/update/${id}`, partnerLinkData),

  // 删除单个合作链接
  deletePartnerLink: (id: number) => apiClient.post(`/api/v1/partner-links/delete/${id}`),

  // 批量删除合作链接
  batchDeletePartnerLinks: (ids: number[]) =>
    apiClient.post('/api/v1/partner-links/delete/batch', ids),

  // ===== 商品评价模块 (/api/v1/review) =====

  // 添加商品评价
  addReview: (reviewData: Partial<import('@/types').ProductReview>) =>
    apiClient.post<boolean>('/api/v1/review/add', reviewData),

  // 获取商品评价列表
  getReviewList: (productId: number, page: number = 1, size: number = 20) =>
    apiClient.get<import('@/types').PageInfo<import('@/types').ProductReview>>(
      '/api/v1/review/list',
      {
        params: { productId, page, size },
      },
    ),

  // 获取用户评价记录
  getUserReviewList: (userId: number, page: number = 1, size: number = 20) =>
    apiClient.get<import('@/types').PageInfo<import('@/types').ProductReview>>(
      '/api/v1/review/user-list',
      {
        params: { userId, page, size },
      },
    ),

  // 删除用户评价
  deleteReview: (reviewId: number) => apiClient.post(`/api/v1/review/delete`, { reviewId }),

  // 回复用户评价
  replyReview: (reviewId: number, replyContent: string) =>
    apiClient.post<boolean>('/api/v1/review/reply', { reviewId, replyContent }),

  // 举报不当评价
  reportReview: (reviewId: number, reportReason: string) =>
    apiClient.post('/api/v1/review/report', { reviewId, reportReason }),

  // 获取评价统计信息
  getReviewStatistics: (productId?: number) =>
    apiClient.get<Record<string, number>>('/api/v1/review/statistics', {
      params: { productId },
    }),
}

export default adminService
